package forword;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http 工具类(基于httpclient4.3.x,且不能出现重复的httpcore或者httpclient包)
 * 
 * @author guojian
 *
 */
public class HttpUtils {

	private static BasicCookieStore cookieStore = new BasicCookieStore();
	private static RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
	private static CloseableHttpClient commonHttpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

	/**
	 * 模拟浏览器发送get请求
	 * 
	 * @param url
	 * @return
	 */
	public static byte[] sendGet(String url, HttpServletRequest request) {
		HttpGet httpGet = new HttpGet(url);
		setCommonHeads(httpGet, request);
		try {
			CloseableHttpResponse response = commonHttpclient.execute(httpGet);
			return EntityUtils.toByteArray(response.getEntity());
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * 模拟浏览器发送post请求
	 * 
	 * @param url
	 * @param nvps
	 */
	public static byte[] sendPost(String url, List<NameValuePair> nvps, HttpServletRequest request) {
		HttpPost httpPost = new HttpPost(url);
		setCommonHeads(httpPost, request);
		try {
			if (nvps != null) {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			}
			return EntityUtils.toByteArray(commonHttpclient.execute(httpPost).getEntity());
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * 普通的post请求,封装了请求的参数
	 * 
	 * @param url
	 * @param nameValues
	 * @return
	 */
	public static byte[] commonPost(String url, Map<String, String> nameValues, HttpServletRequest request) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (nameValues != null) {
			for (String name : nameValues.keySet()) {
				nvps.add(new BasicNameValuePair(name, nameValues.get(name)));
			}
		}
		return HttpUtils.sendPost(url, nvps, request);
	}

	/**
	 * 设置请求的头部
	 * 
	 * @param request
	 */
	private static void setCommonHeads(HttpUriRequest request, HttpServletRequest servletRequest) {
		List<Header> headers = new ArrayList<Header>();
		if (servletRequest == null) {
			headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36"));
			headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
			headers.add(new BasicHeader("Connection", "keep-alive"));
			headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		} else {
			Enumeration<String> headerNames = servletRequest.getHeaderNames();
			while (headerNames.hasMoreElements()) {
				String headerName = (String) headerNames.nextElement();
				headers.add(new BasicHeader(headerName, servletRequest.getHeader(headerName)));
			}
		}
		Header[] headersObject = new Header[headers.size()];
		request.setHeaders(headers.toArray(headersObject));
	}

	public static void main(String[] args) {
	}

}
